package other.edan.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.*;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.exception.XsyHttpException;
import com.rkhd.platform.sdk.http.RkhdHttpClient;
import com.rkhd.platform.sdk.http.RkhdHttpData;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.OperateResult;
import other.edan.order.utils.HCXObjectService;
import other.edan.order.utils.Result;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 根据订单生成报价单
 * @Author: 黎炎松
 * @Date: 2025/1/8 09:38
 */
@RestApi(baseUrl = "/edan/quote")
public class CreateQuoteByOrder implements ApprovalEvent {
    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "根据订单生成报价单 ==> ";

    /**
     * 审批触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) throws ScriptBusinessException {
        LOGGER.info(LOGGER_MSG + "触发开始");
        LOGGER.info("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId());

        Long dataId = request.getDataId();
        Result result = startCreateQuote(dataId);

        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(result.getCode() == 200 ? true : false);
        response.setMsg(result.getMsg());
        return response;
    }

    /**
     * 手动创建
     * @param id
     * @return
     */
    @RestMapping(value = "/createQuoteByOrder", method = RequestMethod.POST)
    public Result createQuoteByOrder(@RestQueryParam(name="id") Long id)  {
        LOGGER.info(LOGGER_MSG + "手动触发按钮生成报价单");
        return startCreateQuote(id);
    }

    public static void main(String[] args) throws IOException {
        CreateQuoteByOrder createQuoteByOrder = new CreateQuoteByOrder();
        createQuoteByOrder.startCreateQuote(3720333066672794L);

        // 测试发送通知
        //Order order = new Order();
        //order.setId(3679478499875463L);
        //order = HCXObjectService.get(order);
        //createQuoteByOrder.sendNotification(order, 3695408199998116L);
    }

    /**
     * 根据订单生成报价单
     * @param orderId
     * @return
     */
    public Result startCreateQuote(Long orderId) {
        try {
            LOGGER.info(LOGGER_MSG + "处理开始");
            Order order = new Order();
            order.setId(orderId);
            order = HCXObjectService.get(order);

            // 是否有关联报价单
            Long specialOfferRequest = order.getSpecialOfferRequest__c();
            if (specialOfferRequest != null) {
                LOGGER.info(LOGGER_MSG + "当前订单已关联特价申请，无需处理");
                return Result.success("当前订单已关联特价申请，无需处理", null);
            }

            // 判断明细价格是否有低于价格表价格
            int isCreateQuote = 0;
            double priceListTotal = 0; // 价格表价格
            double orderPriceTotal = 0; // 订单价格
            String sql = "select id,unitPrice,standardPrice,priceTotal,listTotal,productId,unitPrice,quantity,comment " +
                    " from orderProduct where orderId = " + orderId;
            List<OrderProduct> orderProductList = HCXObjectService.queryAll(sql);
            for (OrderProduct orderProduct : orderProductList) {
                // 单价
                Double unitPrice = orderProduct.getUnitPrice();
                if (unitPrice == null) unitPrice = 0.0;

                // 价格表价格
                Double standardPrice = orderProduct.getStandardPrice();
                if (standardPrice == null) standardPrice = 0.0;

                Double priceTotal = orderProduct.getPriceTotal(); // 价税合计
                Double listTotal = orderProduct.getListTotal(); // 原价
                priceListTotal = bgAdd(priceListTotal, listTotal);
                orderPriceTotal = bgAdd(orderPriceTotal, priceTotal);
                if (unitPrice < standardPrice) {
                    isCreateQuote = 1;
                    break;
                }
            }
            if (isCreateQuote == 0) {
                LOGGER.info(LOGGER_MSG + "满足价格策略，无需生成特价申请");
                return Result.success("满足价格策略，无需生成特价申请", null);
            }

            // 生成一次性特价申请(报价单)
            Quote quote = new Quote();
            quote.setEntityType(11010040900001L);
            quote.setOwnerId(order.getOwnerId()); // 所有人
            quote.setContractIntention__c(orderId); // 订单id
            quote.setQuotationEntityRelOpportunity(order.getOpportunityId()); // 销售机会
            quote.setQuotationEntityRelAccount(order.getAccountId()); // 客户名称
            quote.setTerminalHospital__c(order.getAccountId()); // 最终用户
            quote.setPriceListId(order.getPriceId()); // 价格表
            quote.setQuoteRelContact(order.getContactId()); // 联系人
            quote.setDiscount__c(priceListTotal / orderPriceTotal > 0.9 ? 1 : 2); // 折扣： 1: 大于等于9折 2: 小于9折
            OperateResult insert = HCXObjectService.insert(quote);
            Long quoteId = insert.getDataId();

            // 创建报价明细
            List<QuoteLine> crmAddList = new ArrayList<>();
            for (int i = 0; i < orderProductList.size(); i++) {
                OrderProduct orderProduct = orderProductList.get(i);

                QuoteLine quoteLine = new QuoteLine();
                quoteLine.setEntityType(11010041000001L);
                quoteLine.setName(String.valueOf(i + 1)); // 序号
                quoteLine.setQuotationDetailEntityRelQuotationEntity(quoteId); // 报价单
                quoteLine.setQuotationDetailEntityRelProduct(orderProduct.getProductId()); // 产品
                quoteLine.setQuotationDetailEntityRelAccount(order.getAccountId()); // 客户名称
                quoteLine.setPrice(orderProduct.getUnitPrice()); // 单价
                quoteLine.setPricePolicyUnitPrice__c(orderProduct.getStandardPrice()); // 价格表价格
                quoteLine.setQuantity(orderProduct.getQuantity()); // 数量
                quoteLine.setDetailRemarks(orderProduct.getComment()); // 备注
                quoteLine.setPriceListId(order.getPriceId()); // 价格表
                crmAddList.add(quoteLine);
            }
            HCXObjectService.insertBatch(crmAddList);

            // 更新订单上关联的报价单
            Order upOrder = new Order();
            upOrder.setId(orderId);
            upOrder.setSpecialOfferRequest__c(quoteId);
            upOrder.setUnPriceApply__c(1); // 待发起特价申请 (生成报价单后赋值 是)
            HCXObjectService.update(upOrder);

            // 发送信息通知所有人进行提交
            boolean b = sendNotification(order, quoteId);
            if (!b) {
                LOGGER.info(LOGGER_MSG + "发送信息通知异常");
                return Result.success("Sending a message notification is abnormal. Procedure", null);
            }

            LOGGER.info(LOGGER_MSG + "处理成功");
            return Result.success("新增成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(LOGGER_MSG + "处理异常:" + e.getMessage());
            return Result.error("处理异常:" + e.getMessage());
        }
    }


    /**
     * 加
     * @param v1
     * @param v2
     * @return
     */
    public static double bgAdd(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }


    /**
     * 发送通知
     *
     * @param order
     * @param quoteId
     * @return
     * @throws XsyHttpException
     * @throws IOException
     */
    public boolean sendNotification(Order order, Long quoteId) throws IOException {

        JSONObject sendNoticeData = new JSONObject();
        sendNoticeData.put("content", String.format("订单编号：%s 已自动生成特价申请，请前往特价申请模块进行提交审批", order.getPo())); // 发送内容
        sendNoticeData.put("belongId", 409); // 关联对象的id
        sendNoticeData.put("objectId", quoteId); // 关联对象itemId

        // 接收人id
        JSONArray receiversList = new JSONArray();
        JSONObject receiversUser = new JSONObject();
        receiversUser.put("id", order.getOwnerId()); // 发送的用户id
        receiversUser.put("receiverType", 0);
        receiversList.add(receiversUser);
        sendNoticeData.put("receivers", receiversList);

        // 填充消息体参数结构
        JSONArray mergeFieldList = new JSONArray();
        JSONObject mergeField = new JSONObject();
        mergeField.put("type", 1);
        mergeField.put("belongId", 409); // 关联对象的id (特价申请模块)
        mergeField.put("objectId", quoteId); // 关联对象itemId
        mergeFieldList.add(mergeField);
        sendNoticeData.put("mergeFields", mergeFieldList);
        sendNoticeData.put("mergeFieldsIndex", 0);

        LOGGER.info("通知消息数据：" + sendNoticeData.toJSONString());
        RkhdHttpClient instance = RkhdHttpClient.instance();
        RkhdHttpData data = new RkhdHttpData();
        data.setCallString("/rest/notice/v2.0/newNotice");
        data.setCall_type("POST");
        data.putHeader("Content-Type", "application/json");
        data.setBody(JSONObject.toJSONString(sendNoticeData));
        String response = instance.performRequest(data);
        JSONObject responseJson = JSONObject.parseObject(response);
        LOGGER.info("发送通知消息结果：" + responseJson.toJSONString());
        Integer code = responseJson.getInteger("code");
        if (code == null || 200 != code) {
            LOGGER.info("发送通知消息失败");
            return false;
        }
        LOGGER.info("发送通知消息成功：" + response);
        return true;
    }


}
